from game import zz_game
from zz import zz_log, zz_str, zz_code, zz_dingtalk
import time
import re

log = zz_log.of()


class Game(zz_game.ZZ_Game):
    def __init__(self, d):
        super().__init__(d)
        self.game_name = ''
        self.pass_task = []
        self.account_id = None
        self.game_jiajv = None

    def set_game_jiajv(self, game):
        self.game_jiajv = game

    def config_get(self, k, def_val=None):
        r = zz_game.config_to_return()
        account_data = r.get_data(self.account_id)
        if account_data is None:
            account_data = {}

        if not (k in account_data):
            return def_val
        return account_data[k]

    def config_set(self, k, v, not_reset=False):
        """
        配置
        :param not_reset: true:值已存在，不能设置
        """
        r = zz_game.config_to_return()
        account_data = r.get_data(self.account_id)
        if account_data is None:
            account_data = {}

        do_set = True
        if not_reset:
            if k in account_data:
                do_set = False  # 值已存在
        if do_set:
            account_data[k] = v
        zz_game.config_set(self.account_id, account_data)

    def log_msg(self, msg, do_ka_check=True):
        if zz_str.has_any_text(self.game_name):
            msg = f"[{self.game_name}]{msg}"
        super().log_msg(msg, do_ka_check)

    def get_name(self):
        return "京东互动游戏"

    def task_list_open(self):
        """
        打开任务列表
        """
        self.img_click_if_exists("打开任务列表", "./game/img/京东互动游戏/open_task.png", "./game/img/京东互动游戏/task_main.png")
        self.log_msg("已进入任务列表")
        pass

    def task_list_close(self):
        """
        关闭任务列表
        """
        if not self.img_exit("./game/img/京东互动游戏/task_main.png", 3):
            self.log_msg("未打开任务列表")
            return
        self.click_top()
        self.log_msg("已关闭任务列表")
        pass

    def account_info(self):
        """
        进入账户切换界面
        """
        self.click_if_exists('点击设置', '//*[@content-desc="设置"]', '//*[@resource-id="com.jingdong.app.mall:id/fd"]')
        self.swipe_up()
        self.swipe_up()
        while not self.img_exit("./game/img/京东互动游戏/account_change.png", 2):
            self.swipe_up()
        self.img_click_if_exists_xpath('点击切换帐号', "./game/img/京东互动游戏/account_change.png", '//*[@text="账户切换"]')

    def get_account_id(self, back_main=False):
        """
        获取帐户ID
        :param back_main: 【true】操作返回主页；
        """
        self.log_msg("开始获取帐号信息")
        self.account_info()
        items = self.d.xpath('//*[@resource-id="com.jd.lib.login.feature:id/n3"]').all()
        for i in range(len(items)):
            item = items[i]
            self.account_id = item.text
            done = self.config_get("__done")
            if done:
                self.log_msg(f"{self.account_id}-帐号已完成")
                self.account_id = None
                continue
            else:
                if i == 0:
                    self.log_msg(f"{self.account_id}-当前帐号未完成，返回继续任务")
                    break
            back_main = False
            item.click()
            self.log_msg(f"{self.account_id}-帐号切换")
            break

        if back_main:
            self.click_back()
            self.click_back()
        return self.account_id

    def game_info(self):
        """
        获取游戏信息
        """
        items = self.d.xpath('//android.view.View[@text="去完成"]').all()[-2:]
        timeout = 0
        game_name = ''
        game_item = None
        for item in items:
            for tv in item.parent().parent().elem.getchildren():
                game_name = tv.attrib['text']
                if zz_str.is_null_or_empty(game_name):
                    continue
                if str.startswith(game_name, "玩"):
                    if zz_code.arr_find(self.pass_task, game_name, 1):
                        self.log_msg(f"过滤游戏{game_name}")
                        game_item = None
                        break

                    match = re.search(r'(\d+)秒', game_name)  # 获取浏览x秒
                    if match:
                        timeout = match.group(1)
                        game_item = item
                    break
            if game_item is not None:
                break

        if game_item is None:
            self.log_msg("游戏全部完成")
            return True

        self.game_name = game_name
        self.log_msg(f"开始完游戏：{game_name}")
        game_item.click()
        self.d.sleep(2.5)
        if self.img_exit("./game/img/京东互动游戏/task_main.png", 2):
            self.log_msg(f"进入游戏失败")
            return False
        # if self.is_page("com.jingdong.manto.ui.MantoActivity0", 3):
        #     self.log_msg(f"进入游戏失败")
        #     return False

        self.game_play(int(timeout))
        self.game_close()
        return False

    def game_play(self, timeout):
        """
        玩游戏
        @param timeout: 玩游戏时间
        """
        self.log_msg(f"已进入游戏页面，开始玩{timeout}秒")
        deadline = time.time() + timeout + 5
        while True:
            self.swipe_up()
            self.d.sleep(1)
            self.swipe_down()
            self.d.sleep(1)
            left_s = int(deadline - time.time())
            if left_s <= 0:
                self.log_msg("游戏结束")
                break

            self.log_msg(f"继续玩，还需要玩{left_s}秒")
            self.d.sleep(3)

    def game_close(self):
        """
        关闭游戏
        """
        self.log_msg("关闭游戏")
        self.d.xpath('//*[@resource-id="com.jingdong.app.mall:id/aqw"]').click()
        if self.d.xpath('//*[@text="确定"]').wait(2):
            self.log_msg("存在确认弹窗，点击确认")
            self.d.xpath('//*[@text="确定"]').click()
        if self.d.xpath('//*[@text="退出"]').wait(2):
            self.log_msg("存在确认弹窗，点击确认")
            self.d.xpath('//*[@text="退出"]').click()

    def game_get(self):
        """
        获取奖励
        """
        get_ok = False
        while self.img_exit("./game/img/京东互动游戏/get_prize.png", 2):
            self.log_msg("领取奖励")
            self.img_click("./game/img/京东互动游戏/get_prize.png", 2)

            # if not self.img_exit("./game/img/京东互动游戏/task_main.png", 3):
            #     self.log_msg("未打开任务列表")
            #     return
            # self.img_click("./game/img/京东互动游戏/task_main.png", 2)
            # items = self.d.xpath('//android.widget.TextView[@text="领奖励"]').all()
            # if len(items) == 0:
            #     self.log_msg("无领奖励")
            #     break
            # get_ok = True
            # for item in items:
            #     self.log_msg("领取奖励")
            #     item.click()
            #     self.d.sleep(3)
            #     break
            # self.task_list_close()
            # self.task_list_open()
        return get_ok

    def go_game_main(self):
        """
        进入游戏主界面
        """
        # self.log_msg("关闭京东")
        # self.d.app_stop("com.jingdong.app.mall")
        # self.d.sleep(1)
        self.log_msg("打开京东")
        self.d.app_start("com.jingdong.app.mall")
        self.d.sleep(1)
        items = self.d.xpath('//*[@resource-id="com.jingdong.app.mall:id/fl"]').child('android.widget.FrameLayout').all()
        if len(items) < 5:
            self.log_msg("获取底部导航栏失败")
            return False
        self.log_msg("点击我的")
        items[-1].click()
        self.img_exit("./game/img/京东互动游戏/game_index_00.png", 2)  # 等待图片出现
        # 获取
        account_id = self.get_account_id(True)
        if account_id is None:
            self.log_msg("帐号已全部完成")
            return False
        self.config_set('__done', 0, True)
        #
        if self.game_jiajv is not None:
            g_jia = self.game_jiajv
            g_jia.account_id = account_id
            g_jia.handle_main()
            #
            self.log_msg("点击我的")
            items[-1].click()
            self.img_exit("./game/img/京东互动游戏/game_index_00.png", 2)  # 等待图片出现
        #
        if self.click_exists('//*[@resource-id="com.jd.lib.ordercenter.feature:id/x5"]', 3):
            self.log_msg("存在弹窗，点击关闭")

        # self.img_click_if_exists_xpath('点击互动游戏', "./game/img/京东互动游戏/game_index_00.png", '//*[@resource-id="numberIncrementer"]')
        self.img_click_if_exists_page('点击互动游戏', "./game/img/京东互动游戏/game_index_00.png", 'com.jd.lib.babel.view.activity.BabelActivity')

        self.alert_close_by_file("./game/img/京东互动游戏")

        self.game_6_and_hot()

        self.swipe_up()
        self.click_if_exists('点击更多', '//android.view.View[@text="玩更多"]', '//*[@resource-id="wegame-small-game-center"]')
        self.log_msg("已进入游戏主界面")
        return True

    def game_6_and_hot(self):
        if self.d.xpath('//*[@text="已领"]').wait(2):
            self.log_msg("热门任务已处理过")
            return False

        qian_ok = self.click_exists('//*[@text="签到"]', 2)
        if qian_ok:
            self.log_msg("京豆签到成功")
            self.d.sleep(3)

        self.game_6()
        self.d.sleep(2)
        self.log_msg("后退，重新进入")
        self.d.press("back")
        self.img_click_if_exists_xpath('点击互动游戏', "./game/img/京东互动游戏/game_index_00.png", '//*[@resource-id="numberIncrementer"]')
        #
        self.game_hot()
        #
        self.log_msg("后退，重新进入")
        self.d.press("back")
        self.img_click_if_exists_xpath('点击互动游戏', "./game/img/京东互动游戏/game_index_00.png", '//*[@resource-id="numberIncrementer"]')
        #
        self.log_msg("领取奖励-开始")
        while self.click_exists('//*[@text="领取"]', 2):
            self.log_msg("领取奖励")
            self.d.sleep(2)
        self.log_msg("领取奖励-完成")
        return True

    def game_6(self):
        """
        浏览6秒任务
        """

        i = 1
        while not self.d.xpath('//*[@text="领取"]').wait(2):
            if i > 10:
                self.log_msg(f"超出浏览次数，强制结束")
                break
            self.log_msg(f"{i}-点击浏览6s任务")
            # ok = self.xpath_click('//*[@text="浏览6s"]')
            # if not ok:
            #     continue
            self.d.click(410, 925)
            self.d.sleep(2)
            self.game_play(6)

            self.log_msg(f"{i}-点击返回")
            self.d.press("back")
            while not self.d.xpath('//*[@text="fafcfdbb49e37f1f"]').wait(2):
                self.log_msg(f"{i}-点击返回-失败，再试")
                self.d.press("back")
            self.d.sleep(2)
            i = +1
        self.log_msg(f"浏览6秒任务-完成")

    def game_hot(self):
        """
        浏览热门推荐
        """
        mc_index = len(self.d.xpath('//*[@text="东东农场"]').all())
        dou_index = len(self.d.xpath('//*[@text="种豆得豆"]').all())
        red_index = len(self.d.xpath('//*[@text="赚红包"]').all())

        task_list = [
            f'(//*[@text="东东农场"])[{mc_index}]',
            f'(//*[@text="种豆得豆"])[{dou_index}]',
            f'(//*[@text="赚红包"])[{red_index}]',
        ]
        for task_xpath in task_list:
            self.log_msg(f"{task_xpath}-点击任务")
            click_ok = self.xpath_click(task_xpath)
            if not click_ok:
                self.log_msg(f"{task_xpath}-点击任务-失败")
                continue
            self.d.sleep(2)
            self.game_play(6)
            self.log_msg(f"{task_xpath}-点击返回")
            self.d.press("back")
            while not self.d.xpath('//*[@text="fafcfdbb49e37f1f"]').wait(2):
                self.log_msg(f"点击返回-失败，再试")
                self.d.press("back")
            self.swipe_down()
            self.d.sleep(2)
        self.log_msg(f"浏览热门推荐任务-完成")

    def get_num(self):
        """
        奖票数
        """
        num = 0
        if self.d.xpath('(//android.widget.TextView)[11]').wait(2):
            num = self.d.xpath('(//android.widget.TextView)[11]').get_text()
        return num

    def get_jd_dou(self):
        """
        获取京东奖励
        """
        self.task_list_close()
        item_dou = [
            '//*[@text="1分钟"]',
            '//*[@text="5分钟"]',
            '//*[@text="10分钟"]',
            '//*[@text="30分钟"]',
            '//*[@text="60分钟"]',
        ]
        self.log_msg(f"开始领取京豆奖励")
        for item in item_dou:
            self.log_msg(f"领取奖励-{item}")
            if self.d.xpath(item).wait(2):
                self.d.xpath(item).get(2).parent().click()
                self.d.sleep(2)

    def handle_main(self):
        zz_game.config_path_set(f"./jd_game_config.json")
        self.log_msg("等待进入京东小游戏界面")
        go = self.go_game_main()
        if not go:
            return False

        self.log_msg("已进入京东小游戏界面")
        self.game_get()
        get_ok = False
        while True:
            self.game_name = ''
            if not get_ok:  # 领取过，元素发生变化，需要刷新任务列表
                self.task_list_close()
                self.task_list_open()
            game_done = self.game_info()
            if game_done:
                break
            get_ok = self.game_get()
        #
        self.log_msg("已进入京东小游戏已完成")
        self.get_jd_dou()
        num = self.get_num()
        #
        self.config_set('__done', 1)
        self.config_set('num', num)
        #
        self.log_msg("获取票数-发送钉钉")
        msg = f"**京东小游戏任务** \n\n"
        msg += f"帐号：{self.account_id}\n\n"
        msg += f"时间：{zz_code.date_tostring()}\n\n"
        msg += f"奖票数：{num}\n\n"
        title = '京东小游戏任务'
        zz_dingtalk.send_markdown(msg, title)
        return True
